package cn.gaotu.user.service.impl;

import cn.gaotu.basic.constans.BaseConstants;
import cn.gaotu.basic.dto.LoginDto;
import cn.gaotu.basic.dto.SmsCodeDto;
import cn.gaotu.basic.dto.WechatDto;
import cn.gaotu.basic.excepion.BusinessException;
import cn.gaotu.basic.jwt.JwtUtils;
import cn.gaotu.basic.jwt.LoginResult;
import cn.gaotu.basic.jwt.RsaUtils;
import cn.gaotu.basic.util.AjaxResult;
import cn.gaotu.basic.util.HttpUtil;
import cn.gaotu.basic.util.MD5Utils;
import cn.gaotu.basic.util.StrUtils;
import cn.gaotu.system.domain.Menu;
import cn.gaotu.system.mapper.MenuMapper;
import cn.gaotu.system.mapper.PermissionMapper;
import cn.gaotu.user.domain.Logininfo;
import cn.gaotu.user.domain.User;
import cn.gaotu.user.domain.Wxuser;
import cn.gaotu.user.mapper.LogininfoMapper;
import cn.gaotu.user.mapper.UserMapper;
import cn.gaotu.user.mapper.WxuserMapper;
import cn.gaotu.user.service.ILogininfoService;
import cn.gaotu.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import springfox.documentation.spring.web.json.Json;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static cn.gaotu.basic.jwt.JwtUtils.generateTokenExpireInSeconds;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {


    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public Map<String, Object> account(LoginDto dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        Integer type = dto.getType();
        //1.校验
        if (username == null || password == null || type == null) {
            throw new BusinessException("参数为空");
        }
        //2.根据username+type 查询logininfo  然后通过username和type进行查询对应对象 但是要判断三个值
        Logininfo logininfo= logininfoMapper.findByUserAndPhone(username,type);
        //2.1查询不到
        if (logininfo == null) {
            throw new BusinessException("无法查找到此账号");
        }
        //获取盐值然后通过MD5加密比较
        String salt = logininfo.getSalt();
        //通过MD5加密比较
        String key = MD5Utils.encrypByMd5(password + salt);
        return loginSuccessHandler(logininfo);


//        //获取UUID
//        String token = UUID.randomUUID().toString();
//        if (!key.equals(logininfo.getPassword())) {
//            throw new BusinessException("账号或者密码错误");
//        }
//        //存储到redis里面
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        //返回token+logininfo
//        Map<String, Object> map = new HashMap<>();
//        map.put("token", token);
//        //我们是高级开发工程师 ,我们要注意密码问题
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//        map.put("logininfo", logininfo);
    }

    /**
     * 登录成功之后的逻辑
     * @param logininfo
     */
    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        LoginResult loginResult = new LoginResult();
        loginResult.setLogininfo(logininfo);
        //1.判断是否是员工
        if (logininfo.getType() == 1) {
            //我们需要查询出当前登录人对应的菜单+按钮权限
            //4.1菜单权限
            List<Menu> menus=menuMapper.loadMenusByLogininfoId(logininfo.getId());
            //4.2按钮权限
            List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
            //把登录人信息+权限加封装成JWT串,返回给前端
            loginResult.setMenus(menus);
            loginResult.setPermissions(permissions);
        }
        //把登录人信息+权限组合成jwt串,返回给前端
        //获取私钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
        //使用是私钥将loginResult,加密成JWT串
        String token = JwtUtils.generateTokenExpireInMinutes(loginResult, privateKey, 30);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        //我们是高级开发工程师 ,我们要注意密码问题
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        map.put("logininfo", logininfo);
        map.put("menus", loginResult.getMenus());
        map.put("permissions", loginResult.getPermissions());
        return map;
    }

    @Override
    public AjaxResult wechat(WechatDto dto) {
        String code = dto.getCode();
        if (StringUtils.isEmpty(code)) {
            throw new BusinessException("code参数不能为空");
        }
        //1.通过code从微信中获取token+openid
        String tokenUrl = BaseConstants.WecharConstant.TOKEN_URL
                .replace("APPID",BaseConstants.WecharConstant.APPID)
                .replace("CODE",code)
                .replace("SECRET",BaseConstants.WecharConstant.SECRET);
        String strJson = HttpUtil.httpGet(tokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(strJson);
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        //2. 通过openid查询t_wxuser表,判断wxuser表是否存在user_id中不为空
        Wxuser wxuser = wxuserMapper.findByOpenId(openId);
        //2.1 有,userId存在,直接免密登录===第二次之后的扫码登录
        if (wxuser != null && wxuser.getId() != null) {
           Logininfo logininfo = logininfoMapper.findByWxUserId(wxuser.getUserId());
            //获取UUID
//            String token = UUID.randomUUID().toString();
//            //存储到redis里面
//            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//            //返回token+logininfo
//            Map<String, Object> map = new HashMap<>();
//            map.put("token", token);
//            //我们是高级开发工程师 ,我们要注意密码问题
//            logininfo.setPassword(null);
//            logininfo.setSalt(null);
//            map.put("logininfo", logininfo);
//            return AjaxResult.me().setResultObj(map);
            return AjaxResult.me().setResultObj(loginSuccessHandler(logininfo));
        }
        //2.2 没有,这里应该让浏览器跳转到绑定页面,让它自己输入账号密码来绑定完成
        String binderParams = "?accessToken=" + accessToken + "&openId=" + openId;
        return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
    }

    @Override
    public Map<String, Object> binder(WechatDto dto) {
        //1.获取user
        User user = userMapper.findByPhone(dto.getPhone());
        Logininfo logininfo = null;
        //2.判断user是否为空
        if (user != null) {
            logininfo = logininfoMapper.findById(user.getLogininfoId());//??为什么是getid
        } else {
            //3.不存在就生成新的t_user和+t_logininfo
            user = dto2User(dto);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        //3.根据token和openId 去查找微信的基本信息
        String wxUserURL = BaseConstants.WecharConstant.WXUSER_URL.replace("ACCESS_TOKEN", dto.getAccessToken()).replace("OPENID", dto.getOpenId());
        System.out.println(wxUserURL);
        //3.1发送微信的get请求
        String get = HttpUtil.httpGet(wxUserURL);
        //3.2根据微信的基本信息生成wxuser
        Wxuser wxuser = JSONObject.parseObject(get, Wxuser.class);
        //3.3wxuser绑定到user
        wxuser.setUserId(user.getId());
        //3.4保存wxuser
        wxuserMapper.save(wxuser);
        //直接免密登录
        //获取UUID
//        String token = UUID.randomUUID().toString();
//        //存储到redis里面
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        //返回token+logininfo
//        Map<String, Object> map = new HashMap<>();
//        map.put("token", token);
//        //我们是高级开发工程师 ,我们要注意密码问题
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//        map.put("logininfo", logininfo);
//        return map;
        return loginSuccessHandler(logininfo);
    }
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //同名原则拷贝
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User dto2User(WechatDto dto) {
        User user = new User();
        user.setPhone(dto.getPhone());
        user.setUsername(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5 = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setPassword(md5);
        user.setSalt(salt);
        return user;
    }

}
